package com.travelexp;

import java.text.SimpleDateFormat;
import java.util.Calendar;

import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.DatePicker;
import android.widget.EditText;

public class TravelForm extends Activity {
	private TravelData travelData;
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        travelData = new TravelData(this);
        setContentView(R.layout.activity_travel_form);      
    }
   
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_travel_form, menu);
        return true;
    }    
   
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_save:
            	saveTravel();
            	return true;
            case R.id.menu_cancel:
            	finish();
            	return false;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
	
	protected void saveTravel()
	{	
		String newTravel = null;
		String addInfo = null;
		String date = null;
		
		// Get the texts from screen
		EditText editText = (EditText)findViewById(R.id.travel_name);
		newTravel = editText.getText().toString();
		
		// Name can't be empty
		if(newTravel == null || newTravel.compareTo("") == 0)
		{
			errorMessage();
			return;
		}
		
		editText = (EditText)findViewById(R.id.add_info);
		addInfo = editText.getText().toString();

		// Formats the date		
		DatePicker dp = (DatePicker) findViewById(R.id.init_date);
		Calendar cal = Calendar.getInstance();
		cal.set(dp.getYear(), dp.getMonth(), dp.getDayOfMonth());
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		date = dateFormat.format(cal.getTime());
		
		// Insert the travel on database
		long insertResult = travelData.insertTravel(newTravel, addInfo, date, true);
		if(insertResult == TravelData.RESULT_ERROR)
		{
			errorMessage();
			return;
		}
		finish();
	}
	
	// Display to the user the message when something went wrong
	protected void errorMessage()
	{
		// 1. Instantiate an AlertDialog.Builder with its constructor
		AlertDialog.Builder builder = new AlertDialog.Builder(this);

		// 2. Chain together various setter methods to set the dialog characteristics
		builder.setMessage(R.string.msg_error_new_travel)
		       .setTitle(R.string.title_error_new_travel);

		// 3. Get the AlertDialog from create()
		AlertDialog dialog = builder.create();
		
		// 4. Show the dialog
		dialog.show();
	}
}
